package org.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.test.service.AdminService;
import org.test.service.BookService;
import org.test.service.OrdersService;
import org.test.vo.Admin;
import org.test.vo.Book;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller //注解控制器
@RequestMapping("/Order")
public class OrdersController {
    //注入服务层对象
    @Autowired
    OrdersService ordersService;
    @Autowired
    AdminService adminService;
    @Autowired
    BookService bookService;


    //跳转到下单表单页面并传递相应的数据
    @RequestMapping("addOrderForm")
    public String addOrderForm(Model model, String bookname, int price,String bookid){
        model.addAttribute("bookid",bookid);
        model.addAttribute("bookname",bookname);
        model.addAttribute("price",price);
        return "user/user-addOrder";
    }

    //下单
    @RequestMapping("/addOrder")
    public String addOrder(Model model, String bookname,int price,int bookid,int orderNum,String consignee,String address,String contactWay, HttpSession session){
        String username= (String) session.getAttribute("username");
        Admin adminOrder=adminService.getAdminByUname(username);
        Book book = bookService.getBookByBookid(bookid);
        //计算下单总价
        int orderPrice = orderNum * price;
        int state=0;
        //当前获取时间
        Date d = new Date();
        //设置时间格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //把时间转化为String字段
        String now = df.format(d);
        //新增数据信息
        int orders = ordersService.addOrder(adminOrder.getId(),bookid,bookname,orderNum,consignee,address,contactWay,orderPrice,now);
        if (orders!=0){
            model.addAttribute("message","恭喜添加订单成功");
            return "public/message";
        }
        else{
            model.addAttribute("message","添加订单失败");
            return "public/message";
        }
    }

    //删除订单
    @RequestMapping("/deleteOrder")
    public String deleteOrder(Model model, int orderid){
        //调用方法
        int i= ordersService.deleteOrder(orderid);
            model.addAttribute("message","恭喜删除订单成功");
            return "public/message";

    }
}
